<template>
	<view>
		<u-gap></u-gap>
		<view class="content">
			<view class="item">
				<view class="title">持卡人</view>
				<u-input v-model="realName" :style="{flex:1}" height="100" placeholder="请输入持卡人"></u-input>
			</view>
			<view class="item">
				<view class="title">卡号</view>
				<u-input v-model="bankId" :style="{flex:1}" height="100" type="number" placeholder="请输入卡号"></u-input>
			</view>
			<view class="item">
				<view class="title">银行</view>
				<u-input v-model="bankInfo.label" @click="bankState = true" input-align="right" placeholder="请选择银行" :style="{flex:1}"
				 height="100" disabled></u-input>
				<u-icon name="arrow-right" color="#AAAAAA"></u-icon>
			</view>
			<view class="item">
				<view class="title">开户行所在地</view>
				<u-input v-model="addressText" @click="region = true" :style="{flex:1}" input-align="right" height="100"
				 placeholder="请选择开户所在地" disabled></u-input>
				<u-icon name="arrow-right" color="#AAAAAA"></u-icon>
			</view>
			<view class="item">
				<view class="title">支行名称</view>
				<u-input @click="bankInfo == '' ? toast() : $u.route('/pages/other/searchSubBranch/searchSubBranch',{
					parentNumber:bankInfo.value
				})"
				 :style="{flex:1}" v-model="subBranch.bankName" input-align="right" height="100" disabled placeholder="搜索支行名称"></u-input>
				<u-icon name="arrow-right" color="#AAAAAA"></u-icon>
			</view>
		</view>
		<view class="tip">
			*银行卡仅用于APP内提现申请，如需修改进行商户结算银行卡，
			请联系平台客服
		</view>
		<view class="btn">
			<view class="box" @click="submit">
				下一步，提交证件资料
			</view>
			<view class="safe-area-inset-bottom"></view>
		</view>

		<u-select safe-area-inset-bottom :default-value="defaultBankValue" confirm-color="#FF4E46" value-name="bankNumber" title="请选择银行" label-name="bankName"
		 v-model="bankState" :list="bankList" @confirm="choiceBankResult"></u-select>
		<u-select safe-area-inset-bottom :default-value="defaultValue" title="选择省/市/区" confirm-color="#FF4E47" v-model="region" mode="mutil-column-auto"
		 :list="regionList" @confirm="choiceRegion"></u-select>

		<u-popup mode="center" closeable border-radius="20" v-model="show">
			<view class="popup">
				<view class="title">绑定银行卡需要验证您的身份</view>
				<view class="popup-tip">验证码{{time < 60 ? '已' : '将'}}发送至{{phone}}</view>
				<view class="code">
					<u-input v-model="smsCode" placeholder="请输入验证码"></u-input>
					<u-button size="mini" @click="getCode" :custom-style="customSstyle" ripple>{{time < 60 ? time+'s后重新获取' : '获取验证码'}}</u-button>
				</view>
				<view class="determine" @click="bindCard">
					确认绑定银行卡
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import QQMapWX from "@/common/qqmap-wx-jssdk.min";
	let qqmapsdk = ''
	export default {
		data() {
			return {
				show: false,
				region: false,
				realName: '',
				provinceName: '',
				bankId: '',
				bankList: [],
				cityName: '',
				areaName: '',
				defaultBankValue: [0],
				addressText: '',
				smsCode: '',
				bankState: false,
				defaultValue: [0, 0, 0],
				time: 60,
				regionList: [],
				bankInfo: "",
				phone: '',
				subBranch: '',
				customSstyle: {
					backgroundColor: "#F39A52",
					color: "#ffffff",
					border: 'none',
					'margin-left': '30rpx'
				}
			};
		},
		async onLoad(options) {
			let phone = uni.getStorageSync('userInfo').userName
			let reg = new RegExp("(\\d{3})(\\d{4})(\\d{4})");
			phone = phone.replace(reg, "$1****$3")
			this.phone = phone
			qqmapsdk = new QQMapWX({
				key: 'HQSBZ-EMKE5-6N5IW-QYGDQ-U6EMS-P2BOO'
			});
			let bankList = await this.$u.get('banklist/listTop')
			this.bankList = bankList
			this.getRegionList(() => {
				if (options.id) {
					this.type = 'edit'
					this.id = options.id
					this.$u.get('userbankcard/info/' + options.id).then(res => {
						this.subBranch = {
							bankName: res.bankAddress
						}
						this.bankId = res.bankId
						this.realName = res.realName
						this.bankInfo = {
							label: res.bankName
						}
						this.addressText = `${res.provinceName}-${res.cityName}-${res.areaName}`

						let provinceIndex = this.regionList.findIndex(item => item.label == res.provinceName)
						let cityIndex = this.regionList[provinceIndex].children.findIndex(item => item.label == res.cityName)
						let areaIndex = this.regionList[provinceIndex].children[cityIndex].children.findIndex(item => item.label ==
							res.areaName)
						this.defaultValue = [provinceIndex, cityIndex, areaIndex]

						this.defaultBankValue = [this.bankList.findIndex(item => item.bankName == res.bankName)]

						// let provinceId = this.regionList.filter(item => item.label == res.provinceName)
						// let cityId = this.regionList[provinceIndex].children.findIndex(item => item.label == res.cityName)
						// let areaId = this.regionList[provinceIndex].children[cityIndex].children.findIndex(item => item.label ==
						// 	res.areaName)

						this.provinceName = res.provinceName
						this.cityName = res.cityName
						this.areaName = res.areaName
					})
				}
			})
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer)
			}
		},
		methods: {
			bindCard() {
				if (this.smsCode == '') {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					});
					return
				}
				let url = this.type ? 'userbankcard/update' : 'userbankcard/save'
				this.$u.post(url, {
					id: this.type ? this.id : '',
					bankAddress: this.subBranch.bankName,
					bankId: this.bankId,
					realName: this.realName,
					areaName: this.areaName,
					cityName: this.cityName,
					provinceName: this.provinceName,
					bankName: this.bankInfo.label,
					smsCode: this.smsCode
				}).then(res => {
					clearInterval(this.timer)
					this.show = false
					this.time = 60
					var pages = getCurrentPages(); //当前页面栈
					if (pages.length > 1) {
						var beforePage = pages[pages.length - 2]; //获取上一个页面实例对象  
						beforePage.$vm.updateData(); //触发父页面中的方法change()  
					}
					uni.navigateBack()
				})
			},
			async getCode() {
				if (this.time != 60) return
				await this.$u.get('sms/send/identity/' + uni.getStorageSync('userInfo').userName)
				uni.showToast({
					title: '验证码已发送'
				})
				this.timer = setInterval(() => {
					this.time--
					if (this.time <= 0) {
						this.time = 60
						clearInterval(this.timer)
					}
				}, 1000)
			},
			choiceRegion(e) {
				this.provinceName = e[0].label
				this.cityName = e[1].label
				this.areaName = e[2].label
				this.addressText = `${this.provinceName}-${this.cityName}-${this.areaName}`
				let provinceIndex = this.regionList.findIndex(item => item.label == e[0].label)
				let cityIndex = this.regionList[provinceIndex].children.findIndex(item => item.label == e[1].label)
				let areaIndex = this.regionList[provinceIndex].children[cityIndex].children.findIndex(item => item.label ==
					e[2].label)
				this.defaultValue = [provinceIndex, cityIndex, areaIndex]
			},
			submit() {
				if (this.realName == '') {
					uni.showToast({
						title: '请输入持卡人',
						icon: 'none'
					});
					return
				}
				if (this.bankId == '') {
					uni.showToast({
						title: '请输入卡号',
						icon: 'none'
					});
					return
				}

				var reg = /^\d{19}$/g; // 以19位数字开头，以19位数字结尾  
				if (!reg.test(this.bankId)) {
					uni.showToast({
						title: '请输入正确的银行卡号',
						icon: 'none'
					});
					return
				}

				if (this.bankInfo == '') {
					uni.showToast({
						title: '请先选择银行',
						icon: "none"
					});
					this.bankState = true
					return
				}
				if (this.addressText == '') {
					uni.showToast({
						title: '请选择开户所在地',
						icon: "none"
					});
					this.region = true
					return
				}
				if (this.subBranch == '') {
					uni.showToast({
						title: '请填入支行名称',
						icon: "none"
					});
					return
				}
				this.show = true
				this.getCode()
			},
			toast() {
				uni.showToast({
					title: '请先选择银行',
					icon: "none"
				});
				this.bankState = true
			},
			choiceBankResult(e) {
				this.bankInfo = e[0]
			},
			reverseGeocoder(latitude, longitude) {
				const self = this
				qqmapsdk.reverseGeocoder({
					location: `${latitude},${longitude}`,
					success(res) {
						if (res.status == 0) {
							let {
								address_component
							} = res.result
							let provinceIndex = self.regionList.findIndex(item => item.label == address_component.province)
							let cityIndex = self.regionList[provinceIndex].children.findIndex(item => item.label == address_component.city)
							let areaIndex = self.regionList[provinceIndex].children[cityIndex].children.findIndex(item => item.label ==
								address_component.district)
							self.defaultValue = [provinceIndex, cityIndex, areaIndex]
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					}
				})
			},
			getRegionList(fn = () => {}) {
				const self = this
				let res = uni.getStorageSync('regionList')
				let province = res.filter(item => item.level == 1)
				let city = res.filter(item => item.level == 2)
				let area = res.filter(item => item.level == 3)
				let region = province.map(level1 => {
					return {
						label: level1.areaName,
						value: level1.id,
						parentId: level1.parentId,
						children: city.filter(level2 => level2.parentId == level1.id).map(level2 => {
							return {
								label: level2.areaName,
								value: level2.id,
								parentId: level2.parentId,
								children: area.filter(level3 => level3.parentId == level2.id).map(level3 => {
									return {
										label: level3.areaName,
										value: level3.id,
										parentId: level3.parentId,
									}
								})
							}
						})
					}
				})
				this.regionList = region
				fn()
				let locationPermission = uni.getStorageSync('locationPermission')
				if (locationPermission) {
					this.reverseGeocoder(locationPermission.latitude, locationPermission.longitude)
				} else {
					uni.getLocation({
						type: 'gcj02',
						altitude: true,
						success(res) {
							self.reverseGeocoder(res.latitude, res.longitude)
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.popup {
		padding: 30rpx 50rpx;

		.determine {
			line-height: 80rpx;
			color: #FFFFFF;
			text-align: center;
			margin-top: 100rpx;
			background: linear-gradient(90deg, #FF3868, #FC6161);
			border-radius: 10rpx;
		}

		.code {
			padding-top: 50rpx;
			display: flex;
			align-items: center;
			border-bottom: 1rpx solid #E1E0E0;

		}

		.title {
			padding-top: 40rpx;
			text-align: center;
			font-size: 32rpx;
		}

		.popup-tip {
			font-size: 28rpx;
			margin: 30rpx 0;
			text-align: center;
			color: #AAAAAA;
		}
	}

	.btn {
		position: fixed;
		bottom: 30rpx;
		left: 0;
		width: 100%;
		padding: 0 30rpx;

		.box {
			text-align: center;
			color: #FFFFFF;
			font-size: 30rpx;
			line-height: 100rpx;
			background: linear-gradient(90deg, #FF3868, #FC6161);
			box-shadow: 1rpx 10rpx 15rpx 2rpx rgba(255, 78, 70, 0.3);
			border-radius: 20rpx;
		}
	}

	.tip {
		margin: 0 30rpx;
		margin-top: 20rpx;
		font-size: 24rpx;
		color: #F39A16;
	}

	page {
		background-color: #f7f7f7;
	}

	.content {
		background-color: #FFFFFF;
		margin: 0 30rpx;
		padding: 0 30rpx;
		border-radius: 20rpx;

		.item {
			background-color: #FFFFFF;
			display: flex;
			align-items: center;
			border-bottom: 1rpx solid #E1E1E1;

			&:last-child {
				border-bottom: none;
			}

			.title {
				margin-right: 30rpx;
				font-size: 28rpx;
			}
		}
	}
</style>
